<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Tent_widget extends MY_Widget {
  function __construct(){
    parent::__construct();
  }

  function run(){
    if($HTML = $this->cache->get("post_tent_widget_html")){
      return $HTML;
    }

    $this->load->model("post_model","postModel");
    $this->load->model("user_model","userModel");
    $this->load->model("images_model","imagesModel");
    $this->load->model("brand_model","brandModel");
    $this->load->model("model_model","modelModel");

    $listpost = $this->_getTentPost();

    if(!empty($listpost["list"])){
      foreach ($listpost["list"] as $key => $value) {
        $whereBrand['where']['id'] = $listpost["list"][$key]["postMeta"]['brand'];
        $listpost["list"][$key]["brand"] = $this->brandModel->get($whereBrand);

        $whereModel['where']['id'] = $listpost["list"][$key]["postMeta"]['model'];
        $listpost["list"][$key]["model"] = $this->modelModel->get($whereModel);
      }
      $count = count($listpost["list"]);
    }else{
      $count = 0;
    }
    
    for ($i=$count; $i < 20; $i++) { 
      $listpost["list"][$i] = NULL;
    }

    $this->_assign("listpost",$listpost["list"]);
    $HTML = $this->_fetch("tent");
    $this->cache->write($HTML,"post_tent_widget_html");
    return $HTML;
  }

  private function _getTentPost($limit = 20) {
    $whereUser["where_in"]["group"] = array(6,3);
    $whereUser["limit"] = $limit;
    $userList = $this->userModel->get($whereUser);
    $userList[]["id"] = 5;
    $returnPost["list"] = "";
    foreach ($userList as $key => $value) {
      $userListID[] = $value["id"];
    }

    $where["limit"] = 20;
    $where["order"] = "pos_update_date DESC";
    $where['where']['status'] = 1;
    $where['where_in']['usr_id'] = $userListID;
    
    $posts = $this->postModel->get($where);
    //$returnPost["total"] = count($posts);
    
    if(!empty($posts)){
      foreach ($posts as $key => $value) {
        $returnPost["list"][$key] = $value;
        $returnPost["list"][$key]["categories"] = array_reverse(Util::getCategoryInherit($value["cat_id"]));
        $returnPost["list"][$key]["province"] = Util::getProvince($posts[$key]["province"]);
        $returnPost["list"][$key]["post_type"] = Util::getType($posts[$key]["typ_id"]);
        $whereImage["where"]["pos_id"] = $value["id"];
        $whereImage["order"] = "id ASC";
        $returnPost["list"][$key]["images"] = $this->imagesModel->get($whereImage);
        $returnPost["list"][$key]["comment_count"] = Util::getCommentCount($posts[$key]["typ_id"]);
        $returnPost["list"][$key]["postMeta"] = Util::getPostMeta($posts[$key]["id"]);
      }
      unset($posts);
    }
    return $returnPost;
  }
}